package sicnu.cs.ich.security.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sicnu.cs.ich.security.domain.entity.Permission;
import sicnu.cs.ich.security.domain.entity.Role;
import sicnu.cs.ich.security.mapper.PermissionMapper;
import sicnu.cs.ich.security.service.IRoleService;
import sicnu.cs.ich.security.util.CollectionUtil;
import sicnu.cs.ich.security.service.IPermissionService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/12/3-15:42
 **/
@Service
@Slf4j
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private IRoleService roleService;
    /**
     * 获取用户的权限树
     */
    @Override
    public List<Permission> getUserPermissionMenu(Integer userId) {
        var role = roleService.getUserRole(userId);
        var permissions = permissionMapper.findPermissionsByRoles(role.stream().map(Role::getId).collect(Collectors.toList()));
        return CollectionUtil.permissionToMenu(permissions);
    }

    /**
     * 获取用户的权限树
     */
    @Override
    public List<Permission> getUserPermissionTree(Integer userId) {
        var role = roleService.getUserRole(userId);
        var permissions = permissionMapper.findPermissionsByRoles(role.stream().map(Role::getId).collect(Collectors.toList()));
        return CollectionUtil.permissionToTree(permissions);
    }

    /**
     * 获取用户的权限列表
     */
    @Override
    public List<Permission> getUserPermissions(Integer userId) {
        var role = roleService.getUserRole(userId);
        return permissionMapper.findPermissionsByRoles(role.stream().map(Role::getId).collect(Collectors.toList()));
    }

    /**
     * 获取所有权限（树状）
     */
    @Override
    public List<Permission> getPermissions() {
        return permissionMapper.findPermission();
    }

    /**
     * 获取角色权限
     */
    @Override
    public List<Permission> getRolePermission(List<Integer> roleIds) {
        return permissionMapper.findPermissionsByRoles(roleIds);
    }

}
